//
//  TaiZhangManagerViewController.m
//  YunGui
//
//  Created by User on 16/4/13.
//  Copyright © 2016年 hanen. All rights reserved.
//

#import "TaiZhangManagerViewController.h"
#import "ManagerNoticeBtnView.h"
#import "TopBtn.h"
#import "MJRefresh.h"
#import "SideMenuUtil.h"
#import "TaiZhangmanagerCell.h"
#import "VisitListCell.h"
#import "TaiZhangDetailController.h"
#import "TaiZhangListModel.h"
#import "TaiZhangModel.h"
#import "HYMDatePicker.h"

#define Height(msg) [UIView getHeight:msg]
#define Width(msg) [UIView getWidth:msg]
#define LableHeight 20.0f

@interface TaiZhangManagerViewController ()<HYMDatePickerDelegate,ManagerNoticeBtnViewDelegate,UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
{
    ManagerNoticeBtnView *btnView;
    
    UITableView       *_tableView;
    
    //    TopBtn   *_clickbtn;
    
    UIButton  *_newSubdistrictBtn;
    UIButton *righB;
    
    int  role ;
    NSMutableArray *mineArray;
    NSMutableArray *expandArray;
    NSMutableArray *TaizhangArray;
    int  type;//区分点击的各个部分
    
    NSString * SelectedType;
    NSMutableDictionary *paramDic;
    NSMutableArray *TaizhangIdArr;
    //日历
    UIView *datePickView;
    
    UILabel *Startweek;
    UILabel *Startyear;
    UILabel *Startmonth;
    UILabel *Endweek;
    UILabel *Endyear;
    UILabel *Endmonth;
    int butttag;

    UIView *dateView;
    UIButton *endButton;
    
    UIView *selectedButtonView;
    
    int Page;
    NSString *currentPage;
    NSString *currentNum;
    
    NSString *searchStartDate;
    NSString *searchEndDate;

    //判断日历是否 滑动
    BOOL IsScrolled;
    
    int endtType;
    int time;
    int YearCount;
    int count;
}
@property (strong, nonatomic) UIView *topView;
@property (strong, nonatomic) UIView *searchView;
@property (strong, nonatomic) UIButton *selectBtn;
@property (strong, nonatomic) UIButton *selectListBtn;
@property (strong, nonatomic) UITextField *searchFld;
@property (strong, nonatomic) UIButton *searchImgBtn;
@property (strong, nonatomic) UIView *searchListView;
@property (strong, nonatomic) UISearchBar *searchBar;
@property (nonatomic) BOOL isSearching;


@property (nonatomic, strong) NSString *month;
@property (nonatomic, strong) NSString *year;
@property (nonatomic, strong) NSDate   *date;

@end

@implementation TaiZhangManagerViewController
@synthesize revealController;
- (void)viewWillDisappear:(BOOL)animated
{
    time = 0;
    count = 0;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    Page = 1;
    endtType = 1;
    
    YearCount = CHOOSE_YEAR_COUNT;
    
    SelectedType = @"all";
    currentPage = @"1";
    SelectedType = @"all";
    self.view.backgroundColor = GrayBackColor;
    
    [ViewTool setNavigationBar:self.navigationController.navigationBar];
    self.navigationItem.title = @"台账管理";

    mineArray  = [NSMutableArray array];
    expandArray = [NSMutableArray array];
    TaizhangArray = [NSMutableArray array];
    TaizhangIdArr = [NSMutableArray array];
    [SideMenuUtil addViewGesture:self revealController:revealController];
    
    righB = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, [UIView getWidth:20], [UIView getWidth:20])];
    righB.hidden = YES;
    [righB setBackgroundImage:[UIImage imageNamed:@"search.png"] forState:UIControlStateNormal];
    [righB addTarget:self action:@selector(clickSearch:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barbtn = [[UIBarButtonItem alloc] initWithCustomView:righB];
    self.navigationItem.rightBarButtonItem = barbtn;
    
    self.navigationItem.leftBarButtonItem=[ViewTool getListBarButtonItemWithTarget:self WithAction:@selector(sideLeftButton_selector:)];

    int roleID = [[[NSUserDefaults standardUserDefaults] objectForKey:@"roleId"] intValue];
    if (roleID == 4) {
        role =0 ;
    }else if (roleID == 2){
        role = 1 ;
    }else if(roleID == 1){
        role = 2;
    }
    //    role = 0; //0 是商务经理 1 城市总监 2管理者
    if (role == 0) {
        type = 1;
    }
    if (role == 1) {
        type = 1;//暂时现请求辖区数据 只有辖区小区的数据
    }
    if(role == 2){
        type = 1;
    }

    [self createCalendar];
    [self addTopBtnView];
    [self creatButton];
    [self addTableview];
    [self createSearchView];
    
}
#pragma mark --顶上的按钮
- (void)addTopBtnView
{
    btnView = [[ManagerNoticeBtnView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 38)];
    if (role == 0) {//高级经理
        btnView.btnTitleArray = @[@"办事处统计",@"台账列表"];
    }else if(role == 1){//城市总监
        btnView.btnTitleArray = @[@"办事处统计",@"台账列表"];
    }else if(role == 2){ //管理者
        btnView.btnTitleArray = @[@"办事处统计",@"台账列表"];
    }
    //btnView.btnTitleArray = @[@"我的小区",@"拓展小区",@"在谈小区"];
    btnView.backgroundColor = BlueColor;
    btnView.delegate = self;
    btnView.titleColor = [UIColor whiteColor];
    [self.view addSubview:btnView];
    
    dateView = [[UIView alloc] initWithFrame:CGRectMake(0, btnView.maxY, kScreenWidth, 195)];
    dateView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:dateView];
    
    UIButton *DatePickButt = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth/2.0-Width(40), 5, Width(80), 30)];
    [DatePickButt setTitle:@"日期选择" forState:UIControlStateNormal];
    [DatePickButt setTitleColor:GRAYCOLOR forState:UIControlStateNormal];
    DatePickButt.titleLabel.textAlignment = NSTextAlignmentCenter;
    [dateView addSubview:DatePickButt];
    
    //获取当天所在的 年 月 日 星期
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
    NSDateFormatter *inputFormatter= [[NSDateFormatter alloc] init];
    [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh"]];
    inputFormatter.dateFormat = @"EE";
    
    NSString * week = [inputFormatter stringFromDate: [NSDate date]];
    NSString *day = [NSString stringWithFormat:@"%d",(int)[dateComponent day]];
    if ([day intValue] < 10) {
        day = [NSString stringWithFormat:@"0%d",(int)[dateComponent day]];
    }
    
    NSString *month = [NSString stringWithFormat:@"%d",(int)[dateComponent month]];
    if ([month intValue] < 10) {
        month = [NSString stringWithFormat:@"0%d",(int)[dateComponent month]];
    }
    NSString *year = [NSString stringWithFormat:@"%d",(int)[dateComponent year]];
    
    Startweek = [ViewTool getLabelWith:CGRectMake(DatePickButt.x - Width(65), DatePickButt.maxY+3, Width(30), 30) WithTitle:week WithFontSize:14 WithTitleColor:GRAYCOLOR WithTextAlignment:NSTextAlignmentLeft];
    Startmonth = [ViewTool getLabelWith:CGRectMake(Startweek.x, Startweek.maxY, Width(100), 30) WithTitle:[NSString stringWithFormat:@"%@.%@",month,day] WithFontSize:26 WithTitleColor:UIColorFromRGB(0xff7701) WithTextAlignment:NSTextAlignmentLeft];
    Startyear = [ViewTool getLabelWith:CGRectMake(Startweek.x+10, Startmonth.maxY, Width(80), 30) WithTitle:year WithFontSize:14 WithTitleColor:BLACKCOLOR WithTextAlignment:NSTextAlignmentLeft];
    
    UIImageView *dateImage = [[UIImageView alloc] initWithFrame:CGRectMake(kScreenWidth/2.0-12, Startmonth.y, 24, 24)];
    dateImage.image = [UIImage imageNamed:@"Btn_Normal_Riqi"];
    [dateView addSubview:dateImage];
    
    Endweek = [ViewTool getLabelWith:CGRectMake(DatePickButt.maxX + Width(10), DatePickButt.maxY+3, Width(30), 30) WithTitle:week WithFontSize:14 WithTitleColor:GRAYCOLOR WithTextAlignment:NSTextAlignmentLeft];
    Endmonth = [ViewTool getLabelWith:CGRectMake(Endweek.x, Endweek.maxY, Width(100), 30) WithTitle:[NSString stringWithFormat:@"%@.%@",month,day] WithFontSize:26 WithTitleColor:UIColorFromRGB(0xff7701) WithTextAlignment:NSTextAlignmentLeft];
    Endyear = [ViewTool getLabelWith:CGRectMake(Endweek.x+10, Endmonth.maxY, Width(80), 30) WithTitle:year WithFontSize:14 WithTitleColor:BLACKCOLOR WithTextAlignment:NSTextAlignmentLeft];
    searchStartDate = [NSString stringWithFormat:@"%@-%@-%@",year,month,day];
    searchEndDate = [NSString stringWithFormat:@"%@-%@-%@",year,month,day];
    
    WeekString = week;
    dayString = day;
    monthString = month;
    yearString = year;
    
    [dateView addSubview:Startweek];
    [dateView addSubview:Startmonth];
    [dateView addSubview:Startyear];
    
    [dateView addSubview:Endweek];
    [dateView addSubview:Endmonth];
    [dateView addSubview:Endyear];
    
    UIButton *startButt = [[UIButton alloc] initWithFrame:CGRectMake(Startweek.x, Startweek.y, Width(50), 90)];
    startButt.tag = 0;
    [startButt addTarget:self action:@selector(DatepickViewShow:) forControlEvents:UIControlEventTouchUpInside];
    [dateView addSubview:startButt];
    
    UIButton *endButt = [[UIButton alloc] initWithFrame:CGRectMake(Endweek.x, Startweek.y, Width(50), 90)];
    endButt.tag = 1;
    [endButt addTarget:self action:@selector(DatepickViewShow:) forControlEvents:UIControlEventTouchUpInside];
    [dateView addSubview:endButt];
    [self CreatLine:self.view Y:180];
    
}

- (void)creatButton
{
        selectedButtonView = [[UIView alloc] initWithFrame:CGRectMake(0, btnView.maxY, kScreenWidth, 60.0f)];
        selectedButtonView.backgroundColor = UIColorFromRGB(0xffffff);
        [self.view addSubview:selectedButtonView];
        [self.view sendSubviewToBack:selectedButtonView];
    
        NSArray *titleArr = @[@"全部",@"已审批",@"已支付",@"可申请",@"老台账"];
        for (int i = 0; i< titleArr.count; i++) {
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake((5 + (kScreenWidth-[UIView getWidth:60.0f])/titleArr.count)*i + 10+5, 5, (kScreenWidth-20.0f)/titleArr.count, 60 - 10 )];
            
        [btn setTitle:titleArr[i] forState:UIControlStateNormal];
        btn.tag = i;
          
        btn.titleLabel.font = [UIFont systemFontOfSize:14.0f];
            if (i == 3) {
            }
            if (i == 4) {
            }
            
        if (i == 0) {
            [btn setBackgroundImage:[UIImage imageNamed:@"Btn_Normal_Yishenpi"] forState:UIControlStateNormal];
            btn.selected = YES;
            btn.enabled = NO;
            endButton = btn;
            [btn setTitleColor:UIColorFromRGB(0xff7703) forState:UIControlStateNormal];
        }else{
            btn.selected = NO;
            [btn setTitleColor:[UIColor colorWithWhite:0.7 alpha:1] forState:UIControlStateNormal];
        }
        
        [selectedButtonView addSubview:btn];
        [btn addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    [self CreatLine:selectedButtonView Y:60];
}

- (void)CreatLine:(UIView *)view Y:(float)y
{
    UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, y, self.view.width, 15.0f)];
    backView.backgroundColor = UIColorFromRGB(0xf8f8fa);
    
    UIView *line1 = [ViewTool getLineViewWith:CGRectMake(0, 0, kScreenWidth, 1) withBackgroudColor:UIColorFromRGB(0xe6e7eb)];
    [backView addSubview:line1];
    
    UIView *line2 = [ViewTool getLineViewWith:CGRectMake(0, 14, kScreenWidth, 1) withBackgroudColor:UIColorFromRGB(0xe6e7eb)];
    [backView addSubview:line2];
    [view addSubview:backView];
}

- (void)clickBtn:(UIButton *)btn
{
    if (endButton != btn) {
        [endButton setBackgroundImage:nil forState:UIControlStateNormal];
        [endButton setTitleColor:[UIColor colorWithWhite:0.7 alpha:1] forState:UIControlStateNormal];
        endButton.selected = NO;
        endButton.enabled = YES;
        btn.enabled = NO;
        [btn setBackgroundImage:[UIImage imageNamed:@"Btn_Normal_Yishenpi"] forState:UIControlStateNormal];
        [btn setTitleColor:UIColorFromRGB(0xff7703) forState:UIControlStateNormal];
        endButton = btn;
        btn.selected = YES;
    }
    if (btn.tag == 0) {
        SelectedType = @"all";
    }else if (btn.tag == 1){
        SelectedType = @"complete";
    }
    else if (btn.tag == 2){
        SelectedType = @"payed";
    }
    else if (btn.tag == 3){
        SelectedType = @"applyed";
    }
    else if (btn.tag == 4){
        SelectedType = @"old";
    }
    [SVProgressHUD showWithStatus:@"加载中"];
    [self loadNewData];
    [self.view bringSubviewToFront:_topView];
}

- (void)createCalendar
{
    datePickView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    [self.view addSubview:datePickView];
    
    UIView *BGview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-220-64)];
    BGview.backgroundColor = [UIColor blackColor];
    BGview.alpha = 0.6;
    [datePickView addSubview:BGview];
    
    UIView *DownBgview = [[UIView alloc] initWithFrame:CGRectMake(0, BGview.maxY, kScreenWidth, 220)];
    DownBgview.backgroundColor = [UIColor whiteColor];
    [datePickView addSubview:DownBgview];
    
    UIButton *yesButton = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth - 70, 0, 60, 40)];
    [yesButton setTitle:@"确定" forState:UIControlStateNormal];
    [yesButton setTitleColor:BLACKCOLOR forState:UIControlStateNormal];
    yesButton.tag = 0;
    yesButton.titleLabel.font = [ViewTool getFont:15.0f];
    [yesButton addTarget:self action:@selector(ButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [DownBgview addSubview:yesButton];
    
    UIButton *noButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 0, 60, 40)];
    [noButton setTitle:@"取消" forState:UIControlStateNormal];
    [noButton setTitleColor:GRAYCOLOR forState:UIControlStateNormal];
    noButton.tag = 1;
    noButton.titleLabel.font = [ViewTool getFont:15.0f];
    [noButton addTarget:self action:@selector(ButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [DownBgview addSubview:noButton];
    
    UILabel *upXian = [[UILabel alloc] initWithFrame:CGRectMake(0, noButton.maxY, kScreenWidth, 1)];
    upXian.backgroundColor = GRAYLINECOLOR;
    [DownBgview addSubview:upXian];
    
    HYMDatePicker *datePick = [[HYMDatePicker alloc] init];
    datePick.frame = CGRectMake(0, upXian.maxY , kScreenWidth, DownBgview.height -70);
    datePick.delegateDiy = self;
    [datePick selectRow:YearCount inComponent:0 animated:NO];
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSDayCalendarUnit|NSMonthCalendarUnit;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
    int day = (int)[dateComponent day];
    int month = (int)[dateComponent month];
    
    [datePick selectRow:YearCount-1 inComponent:0 animated:NO];
    [datePick selectRow:month-1 inComponent:1 animated:NO];
    [datePick selectRow:day-1 inComponent:2 animated:NO];
    
    [DownBgview addSubview:datePick];
    
}
- (void)ButtonClick:(UIButton *)butt
{
    if (IsScrolled == NO) {
        if (butt.tag == 1) {
            [self.view sendSubviewToBack:datePickView];
            return;
        }else{
            if (butttag == 0) {
                [self datepickstart];
                
            }else if (butttag == 1){
                [self datepickend];
            }
        }
    }
    if (butt.tag == 0) {
        if (butttag == 0) {
            NSArray *endArr = [Endmonth.text componentsSeparatedByString:@"."];
            int endM = [[endArr objectAtIndex:0] intValue];
            int endD = [[endArr objectAtIndex:1] intValue];
            
            if ([yearString intValue] > [Endyear.text intValue]) {
                [Tools showMessage:@"起始日期不能大于结束日期" view:self];
                return;
            }
            if ([yearString intValue] == [Endyear.text intValue]){
                if ([monthString intValue] > endM) {
                    [Tools showMessage:@"起始日期不能大于结束日期" view:self];
                    return;
                }
                if ([monthString intValue] == endM){
                    if ([dayString intValue] > endD) {
                        [Tools showMessage:@"起始日期不能大于结束日期" view:self];
                        return;
                    }
                }
            }
            [self datepickstart];
        }
        else{
            NSArray *startArr = [Startmonth.text componentsSeparatedByString:@"."];
            int startM = [[startArr objectAtIndex:0] intValue];
            int startD = [[startArr objectAtIndex:1] intValue];
            
            if ([yearString intValue] < [Startyear.text intValue]) {
                [Tools showMessage:@"结束日期不能小于起始日期" view:self];
                return;
            }
            if ([yearString intValue] == [Startyear.text intValue]){
                if ([monthString intValue] < startM) {
                    [Tools showMessage:@"结束日期不能小于起始日期" view:self];
                    return;
                }
                if ([monthString intValue] == startM){
                    if ([dayString intValue] < startD) {
                        [Tools showMessage:@"结束日期不能小于起始日期" view:self];
                        return;
                    }
                }
            }
            [self datepickend];
        }
        [SVProgressHUD showWithStatus:@"加载中"];
        count ++;
        [TaizhangArray removeAllObjects];
        [self getTaiZhangBypage:@"1" pageNum:@"10"];
        IsScrolled = NO;
    }
    else if (butt.tag == 1)
    {
        [self.view sendSubviewToBack:datePickView];
    }
}
- (void)datepickstart
{
    Startweek.text = WeekString;
    Startmonth.text = [NSString stringWithFormat:@"%@.%@",monthString,dayString];
    Startyear.text = yearString;
    searchStartDate = [NSString stringWithFormat:@"%@-%@-%@",yearString,monthString,dayString];
    [self.view sendSubviewToBack:datePickView];
}
- (void)datepickend
{
    Endweek.text = WeekString;
    Endmonth.text = [NSString stringWithFormat:@"%@.%@",monthString,dayString];
    Endyear.text = yearString;
    searchEndDate = [NSString stringWithFormat:@"%@-%@-%@",yearString,monthString,dayString];
    [self.view sendSubviewToBack:datePickView];
}

- (void)currentSelectedDate:(NSString *)yearStr month:(NSString *)monthStr day:(NSString *)dayStr{
    
    IsScrolled = YES;
    
    NSString *dateStr = [NSString stringWithFormat:@"%@%@%@",yearStr,monthStr,dayStr];
    
    NSDateFormatter *inputFormatter= [[NSDateFormatter alloc] init];
    
    [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh"]];
    
    [inputFormatter setDateFormat:@"yyyyMMdd"];
    
    NSDate*inputDate = [inputFormatter dateFromString:dateStr];
    
    inputFormatter.dateFormat = @"EE";
    NSString * weekString = [inputFormatter stringFromDate: inputDate];
    yearString = yearStr;
    monthString = monthStr;
    dayString = dayStr;
    WeekString = weekString;
    

}

- (void)DatepickViewShow:(UIButton *)butt
{
    butttag = (int)butt.tag;
    [self.view bringSubviewToFront:datePickView];
}

- (void)showSearchView{
    
    if (_topView.hidden) {
        _topView.hidden = NO;
        _searchListView.hidden = YES;
    }else{
        _topView.hidden = YES;
        _searchListView.hidden = YES;
    }
}

- (void)showSelectList:(UIButton *)button{
    
}

- (void)hideSearchBtn{
    
}

- (UIButton *)getButtonWithFrame:(CGRect)frame withTitle:(NSString *)title {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = frame;
    [button setTitle:title forState:UIControlStateNormal];
    
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    
    [button setTitleColor:UIColorFromRGB(0xa1a2a7) forState:UIControlStateNormal];
    button.titleLabel.font= [UIFont systemFontOfSize:16.0f];
    return button;
}

//创建头部视图
-(void)createSearchView
{
    CGFloat searchViewHight = 60.0f;
    
    _topView = [[UIView alloc] initWithFrame:CGRectMake(0, btnView.maxY, self.view.width, searchViewHight)];
    [self.view addSubview:_topView];
    
    UIView *searchView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, searchViewHight)];
    [searchView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"Btn_Normal_Sousuodi.png"]]];
    
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 10, self.view.width-40, searchView.height-20)];
    imgView.image = [UIImage imageNamed:@"Btn_Normal_Sousuokuang.png"];
    
    _searchFld = [[UITextField alloc] initWithFrame:CGRectMake(imgView.x+10,imgView.y,imgView.width,imgView.height)];
    _searchFld.placeholder = @"网点编号/小区名称";
    _searchFld.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    
    _searchFld.returnKeyType = UIReturnKeySearch;
    
    [_searchFld setValue:LEFTLINECOLOR forKeyPath:@"_placeholderLabel.textColor"];
    [_searchFld setValue:[UIFont systemFontOfSize:16.0f] forKeyPath:@"_placeholderLabel.font"];
    _searchFld.delegate = self;
    
    UIImageView *bgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, _searchListView.width, _searchListView.height)];
    bgView.image = [UIImage imageNamed:@"Btn_Normal_Shaixuan.png"];
    
    [searchView addSubview:imgView];
    [searchView addSubview:_searchFld];
    [searchView addSubview:_searchImgBtn];
    
    [_topView addSubview:searchView];
    
    _topView.hidden = YES;

}
//点击搜索框中的搜索
- (void)SearchButton
{
    [TaizhangIdArr removeAllObjects];
    [expandArray removeAllObjects];
    [SVProgressHUD showWithStatus:@"搜索中"];
    [self getTaiZhangListByType:SelectedType page:currentPage pageNum:@"10" search:_searchFld.text];
}
- (void)changeNoticeView:(NSInteger)tag
{
    for (int i = 0; i < btnView.btnTitleArray.count; i++) {
        TopBtn *btn = [btnView viewWithTag:9966 + i];
        
        if (tag == 9966 + i) {
            btn.lineView.backgroundColor = YELLOWBTNCOLOR;
            
        }else{
            btn.lineView.backgroundColor = BlueColor;
        }
    }
        if (tag == 9966) {
            type = 1;
            righB.hidden = YES;
            [self.view sendSubviewToBack:_topView];
            _newSubdistrictBtn.hidden = YES;
        }else{
            type = 2;
            righB.hidden = NO;
            [self.view bringSubviewToFront:_topView];
            _newSubdistrictBtn.hidden = NO;
        }
    if (endtType == type) {
        return;
    }
    if (type == 1) {
        dateView.alpha = 1;
    }else{
        dateView.alpha = 0;
    }
    
    time++;
    if (time == 1) {
        [SVProgressHUD showWithStatus:@"加载中"];
        [self loadNewData];
        endtType = type;
    }

    _tableView.tag = type;
    if (type == 1) {
        [self.view sendSubviewToBack:selectedButtonView];
        
        _tableView.frame = CGRectMake(0, 195, kScreenWidth, kScreenHeight-btnView.height-195-64+btnView.height);
        
    }else if (type == 2){
        [self.view bringSubviewToFront:selectedButtonView];
        [self.view bringSubviewToFront:_topView];
        if (_topView.hidden == YES) {
            _tableView.frame = CGRectMake(0, btnView.maxY+75, kScreenWidth, kScreenHeight - btnView.height - 64 - 75);
        }else{
            _tableView.frame = CGRectMake(0, btnView.maxY+75 + _topView.height, kScreenWidth, kScreenHeight - btnView.height - 64 - 75 - _topView.height);
        }
    }
    [_tableView reloadData];
    NSLog(@"xcacacac %d",(int)_tableView.tag);
    endtType = type;

}

#pragma mark textfield 搜索
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
    if (theTextField == _searchFld) {
        [theTextField resignFirstResponder];
    }
    [self search];
    
    return YES;
}

- (void)search{
    
    if (_searchFld.text == nil || _searchFld.text.length == 0) {
        [Tools showMessage:@"请输入搜索关键字" view:self];
        return;
    }
    currentPage = @"1";
    
    [_searchFld resignFirstResponder];
    [self SearchButton];
}


#pragma mark --搜索框
- (void)clickSearch:(UIButton *)btn
{
    if (type == 2) {
        if (btn.selected == NO) {
            
            _topView.hidden = NO;
            selectedButtonView.frame = CGRectMake(0, btnView.maxY + _topView.height, kScreenWidth, 60.0f);
            _tableView.frame = CGRectMake(0, 60+38 + 15 + _topView.height, kScreenWidth,kScreenHeight-60-38 - 15 -_topView.height -64);
            
            
        }else{
           _searchFld.text = @"";
            _topView.hidden = YES;
            selectedButtonView.frame = CGRectMake(0, btnView.maxY, kScreenWidth, 60.0f);
            _tableView.frame = CGRectMake(0, 60+38 + 15, kScreenWidth, kScreenHeight-60-38 - 15 -64);
            
        }
        btn.selected = !btn.selected;
    }
}

#pragma mark --tableview
- (void)addTableview
{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, selectedButtonView.maxY + 15, kScreenWidth, kScreenHeight - selectedButtonView.maxY - 15) style:UITableViewStylePlain];
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = GrayBackColor;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    [self.view addSubview:_tableView];
    
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            
            [self loadNewData];
        }];
    [_tableView.mj_header beginRefreshing];
   
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreData];
    }];
}

- (void)loadNewData
{
    currentPage = [NSString stringWithFormat:@"%d",1];
    if (type == 1) {
        [TaizhangArray removeAllObjects];
    }else{
        [TaizhangIdArr removeAllObjects];
        [expandArray removeAllObjects];
    }
    [self loadAdminDataWithSeachText:nil];
}

- (void)loadMoreData
{
    Page++;
    currentPage = [NSString stringWithFormat:@"%d",Page];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [self loadAdminDataWithSeachText:_searchFld.text];
        });
}
#pragma mark --请求数据
- (void)loadAdminDataWithSeachText:(NSString *)searchText
{
    if (type == 1) {
        
        [self.view sendSubviewToBack:selectedButtonView];
        _tableView.frame = CGRectMake(0, 195, kScreenWidth, kScreenHeight-btnView.height-195-64+btnView.height);
        [_tableView reloadData];
        [self getTaiZhangBypage:currentPage pageNum:@"10"];

        }else if(type == 2){//获取台账列表的数据
            [self.view bringSubviewToFront:selectedButtonView];
            if (_topView.hidden == YES) {
                 _tableView.frame = CGRectMake(0, btnView.maxY+75, kScreenWidth, kScreenHeight - btnView.height - 64 - 75);
            }else{
            _tableView.frame = CGRectMake(0, 60+38 + 15 + _topView.height, kScreenWidth, kScreenHeight-60-38 - 15 -64 - _topView.height);
            }
            [_tableView reloadData];
        [self getTaiZhangListByType:SelectedType page:currentPage pageNum:@"10" search:_searchFld.text];
    }
}
- (void)getTaiZhangBypage:(NSString *)page pageNum:(NSString *)pageNum
{
    NSString *timearea = [NSString stringWithFormat:@"%@,%@",searchStartDate,searchEndDate];
    
    NSNumber *pageN2 = [NSNumber numberWithUnsignedLong:[pageNum longLongValue]];
    
    paramDic = [NSMutableDictionary dictionaryWithDictionary:@{@"method":@"app.ledger.count",@"page":page,@"pageNum":pageN2}];
    if (count != 0) {
        [paramDic setObject:timearea forKey:@"timearea"];
    }
    
    NSDictionary *paramersDict = [DataTool addSignToDic:paramDic];
    NSLog(@"台账统计的  参数 %@",paramersDict);
    [DataTool postWithUrl:HEAD_URL parameters:paramersDict success:^(id data) {
        id backData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments | NSJSONReadingMutableContainers error:nil];
        NSString *status = [(NSDictionary *)backData objectForKey:@"status"];
        if ([status isEqualToString:@"SUCCESS"]) {

        NSArray *dataArray = backData[@"data"][@"listData"];
        int total = [backData[@"data"][@"total"] intValue];
        if (total== 0) {
            [Tools showMessage:@"数据为空" view:self];
        }
        if (total <10) {
            [_tableView.mj_footer endRefreshingWithNoMoreData];
        }else{
            if (dataArray.count < 10) {
                [_tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                [_tableView.mj_footer endRefreshing];
            }
        }
        
        for (int i = 0; i< dataArray.count; i++) {
            TaiZhangModel *model = [[TaiZhangModel alloc] init];
            [model setValuesForKeysWithDictionary:dataArray[i]];
            [TaizhangArray addObject:model];
        }
        [_tableView.mj_header endRefreshing];
        [SVProgressHUD dismiss];
        [_tableView reloadData];
        }
        else{
            [_tableView.mj_header endRefreshing];
             NSString *msg = [(NSDictionary *)backData objectForKey:@"msg"];
            [SVProgressHUD showErrorWithStatus:msg];
        }
        
    } fail:^(NSError *error) {
        NSLog(@"%@",error.localizedDescription);
        [_tableView.mj_header endRefreshing];
        [SVProgressHUD dismiss];
    }];
}

- (void)getTaiZhangListByType:(NSString *)Type page:(NSString *)page pageNum:(NSString *)pageNum search:(NSString *)searchText
{
    NSNumber *pageN = [NSNumber numberWithUnsignedLong:[page longLongValue]];
    NSNumber *pageN2 = [NSNumber numberWithUnsignedLong:[pageNum longLongValue]];
    if ([_searchFld.text isEqualToString:@""]) {
        paramDic = [NSMutableDictionary dictionaryWithDictionary:@{@"method":@"app.ledger.list.page",@"type":Type,@"page":pageN,@"pageNum":pageN2}];
    }
    else{
    paramDic = [NSMutableDictionary dictionaryWithDictionary:@{@"method":@"app.ledger.list.page",@"type":Type,@"page":pageN,@"pageNum":pageN2,@"search":searchText}];
    }

    NSDictionary *paramersDict = [DataTool addSignToDic:paramDic];
    [DataTool postWithUrl:HEAD_URL parameters:paramersDict success:^(id data) {
        [SVProgressHUD dismiss];
        for (int i = 0; i< 5; i++) {
            
            UIButton *myButton = (UIButton *)[selectedButtonView viewWithTag:i];
            myButton.userInteractionEnabled = YES;
        }
        id backData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments | NSJSONReadingMutableContainers error:nil];
        //NSLog(@"台账列表的数据%@",backData);
        NSString *status = [(NSDictionary *)backData objectForKey:@"status"];
        if ([status isEqualToString:@"SUCCESS"]) {
            
        NSArray *dataArray = backData[@"data"][@"listData"];
        int total = [backData[@"data"][@"total"] intValue];
        if (total== 0) {
            [Tools showMessage:@"数据为空" view:self];
        }
        if (total <10) {
            [_tableView.mj_footer endRefreshingWithNoMoreData];
        }else{
            if (dataArray.count < 10) {
                [_tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                [_tableView.mj_footer endRefreshing];
            }
        }
        
        for (int i = 0; i< dataArray.count; i++) {
            TaiZhangListModel *model = [[TaiZhangListModel alloc] init];
            [model setValuesForKeysWithDictionary:dataArray[i]];
            [expandArray addObject:model];
        }

    }else{
        int code = [[(NSDictionary *)backData objectForKey:@"code"] intValue];
        NSString *msg = [(NSDictionary *)backData objectForKey:@"msg"];
        NSLog(@"台账返回%@%d%@",status,code,msg);
        [Tools showMessage:msg view:self];
        if (code == 999991) {
            [_tableView.mj_footer endRefreshingWithNoMoreData];
        }
    }
        [_tableView.mj_header endRefreshing];
        [_tableView reloadData];
        
    } fail:^(NSError *error) {
        [SVProgressHUD dismiss];
        [Tools showMessage:error.localizedDescription view:self];
        [_tableView.mj_footer endRefreshingWithNoMoreData];
        [_tableView.mj_header endRefreshing];
        NSLog(@"%@",error.localizedDescription);
    }];
}

#pragma mark --tableview代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
   
    if (type == 2){
    return expandArray.count;
    }
    return TaizhangArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
        if (type == 1) {
            TaiZhangmanagerCell *cell = [TaiZhangmanagerCell cellWithTableView:tableView];
            if (TaizhangArray.count != 0) {

            [cell setModel:[TaizhangArray objectAtIndex:indexPath.row]];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            
            //cell.model = mineArray[indexPath.row];
            return cell;
        }else if (type == 2)
        {
            static NSString *CellIdentifier = @"VisitListCell";
            VisitListCell *cell = (VisitListCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) {
                cell = [[VisitListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            }
                cell.selectionStyle = UITableViewCellSelectionStyleGray;
            if (expandArray.count != 0) {
                TaiZhangListModel *model = [expandArray objectAtIndex:indexPath.row];
                cell.visitNum.text=model.branch_no;
                cell.visitSub.text=model.title;
                
                cell.dateImage.image = [UIImage imageNamed:@"Btn_Normal_Liucheng.png"];
                cell.payImage.image = [UIImage imageNamed:@"Btn_Normal_Zhuangtai.png"];
                
                if ([model.check_status isEqualToString:@"1"]) {
                    cell.visitPro.text=@"流程状态:已审批";
                    cell.visitPro.textColor = UIColorFromRGB(0xa4a9b1);
                    cell.dateImage.image = [UIImage imageNamed:@"Btn_Push_Liucheng1.png"];
                    
                }
                else{
                    cell.visitPro.text=@"流程状态:审批中";
                }
                if ([model.pay_status isEqualToString:@"0"]) {
                    cell.visitDate.text=@"付款状态: 未付款";
                }
                else if([model.pay_status isEqualToString:@"1"]){
                    cell.visitDate.text=@"付款状态: 已付款";
                    cell.visitDate.textColor = UIColorFromRGB(0xa4a9b1);
                    cell.payImage.image = [UIImage imageNamed:@"Btn_Push_Zhuangtai1.png"];
                }
                else if([model.pay_status isEqualToString:@"2"]){
                    cell.visitDate.text=@"付款状态: 待确认";
                }
            }
            

            return cell;
        }
    return nil;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (type == 1) {
               
        return;
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    TaiZhangDetailController *detailVC = [[TaiZhangDetailController alloc] init];
    TaiZhangListModel *model = [expandArray objectAtIndex:indexPath.row];
    
    detailVC.districtID = model.DistrictID;
    
    [self.navigationController pushViewController:detailVC animated:YES];
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (type == 1) {
        return [TaiZhangmanagerCell cellHeight];
    
    }
         return 95.0f;
}

// 拉开左侧:点击.
- (void)sideLeftButton_selector:(id)sender {
    
    [self.revealController toggleSidebar:!self.revealController.sidebarShowing duration:kGHRevealSidebarDefaultAnimationDuration];
}

@end
